<template>
  <div class="vxe-container">
    <div>
      <el-row>
        <GButton :is-add-show="false" :is-edit-show="false" :is-del-show="false" :lists="options"
          :is-settings-show="lookSetShow" @selectSettings="selectSettings" />
      </el-row>
      <br>

      <!-- 参数配置 -->
      <el-dialog v-el-drag-dialog :visible.sync="configModal" :close-on-click-modal="false" width="85%"
        class="config-dialog">
        <head-table :config-list="configList" :key-value="key" @updateConfigData="getUpdateConfigData" />
      </el-dialog>

      <!-- SQL弹窗 -->
      <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
        <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
          <el-form-item label="SQL语句" prop="gzsql">
            <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL">确认</el-button>
            <el-button @click="dialogSQLModal = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
    <!-- style=" border:1px solid red;width:100%" -->
    <div style=" margin-top:-20px; ">
      <template v-if="limits.length >= 1 && limits.filter(it => it.FName === '查看').length">
        <vxe-grid ref="xGrid" v-bind="gridOptions"
          :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
          @cell-dblclick="cellDbclick">
          <template #toolbar_buttons>
            <vxe-input v-model="keyword" placeholder="搜索" prefix-icon="vxe-icon-search" clearable
              @keyup.native.enter="getvxetableGenList" />
            <!-- <vxe-select v-model="fstatus" clearable filterable style="width: 126px;" placeholder="请选择审核状态" @change="getvxetableGenList">
              <vxe-option
                v-for="item in statusList"
                :key="item.fstatus"
                :label="item.fname"
                :value="item.fstatus"/>
            </vxe-select> -->
            <vxe-button status="danger" @click="getvxetableGenList">搜索</vxe-button>
            <vxe-button v-if="limits.length >= 1 && limits.filter(it => it.FName === '新增').length" status="primary"
              @click="vxeAdd()">新增 </vxe-button>

            <vxe-button v-if="limits.length >= 1 && limits.filter(it => it.FName === '保存').length" status="primary"
              @click="vxeSave()">保存</vxe-button>
            <vxe-button v-if="limits.length >= 1 && limits.filter(it => it.FName === '导出').length" status="primary"
              @click="vxeExport()">导出</vxe-button>
            <vxe-button v-if="limits.length >= 1 && limits.filter(it => it.FName === '审核').length" status="primary"
              @click="check('1')">审核</vxe-button>
            <vxe-button v-if="limits.length >= 1 && limits.filter(it => it.FName === '反审核').length" status="primary"
              @click="check('0')">反审核</vxe-button>
            <vxe-button status="primary" @click="refresh()">刷新</vxe-button>
          </template>
          <!-- <template #pager>
            <vxe-pager :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
              :current-page.sync="tablePage.currentPage" :page-size.sync="tablePage.pageSize" :total="tablePage.total"
              @page-change="handlePageChange" />
          </template> -->
        </vxe-grid>
      </template>
    </div>

    <!-- 机型明细 -->
    <FmodelDetail
      :fmodel-dialog="fmodelDialog"
      @handleSelectionChange="fmodelSelectionChange"
      @downData="fmodelDownData"
      @handleSizeChange="fmodelSizeChange"
      @handleCurrentChange="fmodelCurrentChange" />
  </div>
</template>
<script>
let FRepKey = ''
let opername = ''

import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
// import { tableConfig, apiSql, apiFileSave, getFSCRSetList, vxetableConfig } from '../../api/account'
import { getFSCRSetList, getFSCRSetSave, vxetableConfig, vxetableGenList, vxetableGenAdd, cenShuSave, tableConfig, apiSql, apiFileSave } from '../../api/account'
import { configColumn, checkStatus } from '../../api/salary'
import { download } from '../../mixins/download.js'
import { common } from '../../mixins/common'
import VXETablePluginShortcutKey from 'vxe-table-plugin-shortcut-key'
import '../../styles/vxetable.scss'
import HeadTable from '../salary/headTable/index.vue'
import { FBMluruMx } from '../../api/gen'

VXETable.use(VXETablePluginShortcutKey, {
  // 功能键设置
  setting: {
    'table.edit.tab.rightMove': 'Enter',
    'table.edit.tab.leftMove': 'shift + Tab'

  }
})

export default {
  components: {
    HeadTable
  },
  mixins: [download, common],
  data () {
    return {

      columnData: [],
      opername: '',
      aaValue: '',
      oriColumnData: [],

      configList: [],
      configModal: false,
      menusList: [],
      limits: [],
      options: [],
      lookSetShow: false,
      key: 0,
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {
      },

      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 20
      },
      vxeDisabled: false,

      keyword: '',
      gridOptions: {
        border: true,
        showHeaderOverflow: true,
        showOverflow: true,
        showFooterOverflow: true,
        keepSource: true,
        autoResize: true,
        resizable: true,

        height: this.heightGD(),
        showFooter: true,
        round: true,
        size: 'mini',

        id: 'full_edit_1',
        rowId: 'id',
        rowConfig: {
          isHover: true
        },
        // columnConfig: {
        //   resizable: true
        // },

        // 自定义列配置项
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },

        keyboardConfig: {
          isEnter: true,
          isArrow: true
        },

        // formConfig: {
        //   titleWidth: 100,
        //   titleAlign: 'right',
        //   items: [
        //     // { field: 'name', title: '名称', span: 8, titlePrefix: { message: 'app.body.valid.rName', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' }}},
        //     // { field: 'email', title: '邮件', span: 8, titlePrefix: { useHTML: true, message: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入邮件' }}},
        //     // { field: 'nickname', title: '昵称', span: 8, itemRender: { name: '$input', props: { placeholder: '请输入昵称' }}}
        //     // { field: 'role', title: '角色', span: 8, folding: true, itemRender: { name: '$input', props: { placeholder: '请输入角色' }}},
        //     // { field: 'sex', title: '性别', span: 8, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'vxe-icon-info-circle-fill' }, itemRender: { name: '$select', options: [] }},
        //     // { field: 'age', title: '年龄', span: 8, folding: true, itemRender: { name: '$input', props: { type: 'number', min: 1, max: 120, placeholder: '请输入年龄' }}}
        //     // { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' }}, { props: { type: 'reset', content: '重置' }}] }}
        //   ]
        // },

        toolbarConfig: {
          custom: true,
          buttons: [
            { code: 'myInsert', name: '新增', icon: 'vxe-icon-square-plus', status: 'success' },
            { code: 'myDelete', name: '删除', icon: 'vxe-icon-delete', status: 'success' },
            { code: 'mySave', name: '保存', icon: 'vxe-icon-save', status: 'success' }
            // { code: 'myInsertTZ', name: '新增跳转', icon: 'vxe-icon-square-plus', status: 'success' }
            // { code: 'myOper', name: '操作', icon: 'vxe-icon-square-down', status: 'success', slots: 'default', dropdowns: [{ code: 'myAA', 'name': 'AA', status: 'info', icon: 'vxe-icon-square-plus-fill' }, { code: 'myBB', 'name': 'BB', status: 'info', icon: 'vxe-icon-square-plus-fill' }] }
          ],
          slots: {
            buttons: 'toolbar_buttons'
          }

        },
        columns: [],
        data: [],

        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },

        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true, // 是否显示单元格新增与修改状态
          showIcon: false // 是否显示列头编辑图标
          // activeMethod: this.activeRowMethod
        }

      },

      fmodelDialog: {
        fstatuscg: true,
        fmodel: '',
        fdetailModal: false,
        // 批量删除
        checkData: [],
        selectedData: [],
        // 表头、表格设置
        tableData: [],
        tableList: [],
        defaultFormThead: [],
        formThead: [],
        dialogThead: [],
        curData: {},
        listLoading: false,
        // 分页相关变量
        total: 0,
        currentPage: 1,
        // pagesize: 100,
        pagesize: 20,
        pagesizes: [10, 20, 50, 100, 300, 500, 1000, 2000, 3000, 5000, 10000],
        // 导出相关
        header: [],
        headerKeys: [],
        listData: []
      }
    }
  },
  Mounted: {

  },
  computed: {

  },
  async created () {
    FRepKey = this.$route.meta.FRepKey
    this.opername = decodeURIComponent(this.globalDb.fname)
    opername = decodeURIComponent(this.globalDb.fname)

    await this.getvxetableConfig()
    await this.getvxetableGenList()

    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    // 菜单列表（权限）
    const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    this.menusList = menuRes
    if (menuRes.length >= 1) {
      menuRes.map(it => {
        it.children.map(item => {
          if (item.fobjectid === FRepKey) {
            this.$set(this, 'limits', item.child)
          }
        })
      })
    }
  },
  methods: {
    activeRowMethod ({ row, column, columnIndex }) {
      console.log(10000, row, column, columnIndex)
    },

    editDisabledEvent ({ row }) { },

    editClosedEvent ({ row }) {
      //   // this.vxeDisabled = true
      //   console.log(5555, row.fstatus, row.fstatus === 1)
      //   if (row.fstatus === 1) {
      //     this.vxeDisabled = !row.fstatus === 1
      //     console.log(6666, this.vxeDisabled)
      //   }
    },

    // 高度
    heightGD () {
      return (document.body.offsetHeight - 150) + 'px'
    },
    selectSettings (val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    settings () {
      this.configModal = true
      this.getTableConfig()
    },
    async getTableConfig () {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername: this.opername,
          key: FRepKey
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // SQL修改/更新
    async dialogSQL () {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername: this.opername,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL () {
      this.$refs['formSQL'].validate(async (valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = this.opername
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },

    // 更新数据
    async getUpdateConfigData () {
      await this.getTableConfig()
    },

    // 添加表格背景颜色
    footerCellClassName ({ $rowIndex, columnIndex }) {
      // if (columnIndex === 0) {
      if ($rowIndex === 0) {
        // return 'col-blue'
        // }
      }
    },

    // 字段
    async getvxetableConfig () {
      const res = await vxetableConfig(
        {
          FUnControl: -1,
          opername: this.opername,
          FRepKey
        }
      )
      this.oriColumnData = res.Data
      // setTimeout(() => {
      if (res.Data.length > 0) {
        this.columnData.push({
          type: 'seq',
          width: 50,
          fixed: 'left'
        })
        this.columnData.push({
          type: 'checkbox',
          width: 50,
          fixed: 'left'
        })

        for (let i = 0; i < res.Data.length; i++) {
          if (res.Data[i].frepfld === 'fstatus') {
            this.columnData.push({
              field: res.Data[i].frepfld,
              title: res.Data[i].frepcap,
              // formatter: this.formatFstatus,
              width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
              // editRender: { name: 'input', attrs: { placeholder: '' }}
              slots: {
                // 使用 JSX 渲染
                default: ({ row }) => {
                  if (row.fstatus === 1) {
                    return [
                      <el-tag>审核</el-tag>
                    ]
                  }
                }
              }
            })
          } else {
            this.vxeDisabled = false
            if (res.Data[i].falign === 1) {
              if (res.Data[i].fisedit === 1) {
                this.vxeDisabled = true
              }
              this.columnData.push({
                field: res.Data[i].frepfld,
                title: res.Data[i].frepcap,

                headerAlign: 'left',
                align: 'right',

                width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,

                editRender: { name: 'input', attrs: { readonly: Boolean(res.Data[i].fisedit), placeholder: '' } }
              })
            } else {
              if (res.Data[i].fisedit === 1) {
                this.vxeDisabled = true
              }
              this.columnData.push({
                field: res.Data[i].frepfld,
                title: res.Data[i].frepcap,
                // showHeaderOverflow: true,
                // showOverflow: true,
                // resizable: true,
                width: res.Data[i].frepwid > 0 ? res.Data[i].frepwid : 0,
                editRender: { name: 'input', attrs: { readonly: Boolean(res.Data[i].fisedit), placeholder: '' } }
              })
            }
          }
        }
        this.gridOptions.columns = this.columnData

      //  console.log(this.columnData, ' this.columnData')
        // console.log(this.columnData, ' this.columnData')

        this.formThead = res.Data
        // this.tableList = []
        this.formThead.map(item => {
          this.gridOptions.data.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })

        // 获取显示表头键值对
        this.formThead.filter(item => {
          if (!item.frephide) {
            this.header.push(item.frepcap)
            this.headerKeys.push(item.frepfld)
          }
        })
        // // 获取显示表体数据
        // const listData = this.gridOptions.data.slice()
        // listData.map((item, index) => {
        //   this.listData[index] = {}
        //   this.headerKeys.map(it => {
        //     this.listData[index][it] = item[it]
        //   })
        // })

        // 1111
      }
      // }, 1000)
    },

    // formatFstatus(row) {
    //   console.log(row, 88888888888)

    //   }
    // },

    // 刷新
    refresh () {
      window.location.reload()
    },

    // 新增
    vxeAdd () {
      const $grid = this.$refs.xGrid
      $grid.insert({})
    },

    // 导出
    async vxeExport () {
      await this.getAllData()
      await this.exportData()
    },

    // 保存
    async vxeSave () {
      const $grid = this.$refs.xGrid
      const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
      if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
        VXETable.modal.message({ content: ` 更新 ${updateRecords.length} 条`, status: 'warning' })
        return
      }
      // 修改时 是否已审核
      if (updateRecords.length > 0) {
        const isFstatus = updateRecords.filter(it => Number(it.fstatus) === 1)
        if (isFstatus.length) {
          this.$message({
            message: '已审核，不能修改！',
            type: 'error'
          })
          return
        }
      }

      // console.log(insertRecords, removeRecords, updateRecords, insertRecords.length > 0, updateRecords.length > 0, removeRecords.length > 0)
      try {
        // await vxetableGenAdd({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords })
        // const res = await cenShuSave({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords })
        const res = await getFSCRSetSave({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords })
        if (res.Error === 0) {
          this.$message({
            type: 'success',
            message: res.Message
          })
          await this.getvxetableGenList()
        } else {
          this.$message({
            type: 'error',
            message: res.Message
          })
        }
      } catch (error) {
        console.log(error)
      }

      VXETable.modal.message({ content: ` 更新 ${updateRecords.length} 条`, status: 'success' })
    },

    // 删除
    async vxeDel () {
      const $grid = this.$refs.xGrid
      if ($grid.getCheckboxRecords().length === 0) {
        VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
        return
      }
      // 判断已审核
      const dataTemp = $grid.getCheckboxRecords()
      const isFstatus = dataTemp.filter(it => Number(it.fstatus) === 1)
      if (isFstatus.length) {
        this.$message({
          message: '已审核，不能删除！',
          type: 'error'
        })
        return
      }

      const { removeRecords } = $grid.getRecordset()
      $grid.removeCheckboxRow()
      const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
      if (res.Error === 0) {
        VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
        this.getvxetableGenList()
      }
    },

    // 1—审核，0—反审
    async check (Fstatus) {
      const $grid = this.$refs.xGrid
      if ($grid.getCheckboxRecords().length === 0) {
        VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
        return
      }
      const checkData = []
      $grid.getCheckboxRecords().map(it => {
        checkData.push(it.fid)
      })

      if (Number(Fstatus) === 1) {
        this.$confirm('是否审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(async () => {
          try {
            const res = await checkStatus({
              db: this.globalDb.db,
              opername: decodeURIComponent(this.globalDb.fname),
              loginname: decodeURIComponent(this.globalDb.fname),
              FRepKey,
              Fstatus, // 1—审核，0—反审
              fid: checkData.join(',')

            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              await this.getvxetableGenList()
            } else {
              this.loadingForm = false
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: checkData.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getvxetableGenList()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },

    // 内容列表
    async getvxetableGenList () {
      // const param = { FRepKey, opername, keyword: this.keyword, fstatus: this.fstatus, page: this.tablePage.currentPage, pageSize: this.tablePage.pageSize }
      const param = { FRepKey, opername, keyword: this.keyword, fstatus: this.fstatus, }
      // const res = await vxetableGenList(param)
      const res = await getFSCRSetList(param)
      setTimeout(() => {
        this.tablePage.total = res.total
        this.gridOptions.data = res.Data
        // res.Data
      }, 500)
    },
    // 内容列表
    async getAllData () {
      // const param = { FRepKey, opername, keyword: this.keyword, fstatus: this.fstatus, page: this.tablePage.currentPage, pageSize: this.tablePage.total }
      const param = { FRepKey, opername, keyword: this.keyword, fstatus: this.fstatus, }
      // const res = await vxetableGenList(param)
      const res = await getFSCRSetList(param)
      // setTimeout(() => {
      // this.tablePage.total = res.total
      // this.gridOptions.data = res.Data
      // 获取显示表体数据
      console.log(this.gridOptions.data, ' this.gridOptions.data')
      const listData = res.Data.slice()
      console.log(this.total, ' this.total')
      console.log(this.listData, ' this.listData')
      listData.map((item, index) => {
        this.listData[index] = {}
        this.headerKeys.map(it => {
          this.listData[index][it] = item[it]
        })
      })
      // res.Data
      // }, 500)
    },
    // 分页
    // handlePageChange ({ currentPage, pageSize }) {
    //   console.log(22222, currentPage, pageSize)
    //   this.tablePage.currentPage = currentPage
    //   this.tablePage.pageSize = pageSize
    //   this.getvxetableGenList()
    // },

    addressClickEvent (row) {
      VXETable.modal.alert(`address点击事件：${row.address}`)
    },
    // FBumenMX
    // 获取机型明细数据
    async getFBumenMX () {
      try {
        this.fmodelDialog.listLoading = true
        // const res = await genList({
        const res = await FBMluruMx({
          db: this.globalDb.db,
          FRepKey,
          opername,
          fmodel: this.fmodelDialog.fmodel,
          // keyword: '',
          // fstatus: this.fstatus,
          limit: this.fmodelDialog.pagesize,
          page: this.fmodelDialog.currentPage
          // fbrand: this.fbrand
        })
        this.fmodelDialog.listLoading = false
        this.fmodelDialog.tableList = res.Data
        this.fmodelDialog.total = res.total
      } catch (error) {
        this.fmodelDialog.listLoading = false
      }
    },
    // 表头数据
    async getFBumenMXHeader () {
      try {
        this.fmodelDialog.listLoading = true
        this.fmodelDialog.header = []
        this.fmodelDialog.headerKeys = []
        this.fmodelDialog.listData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername,
          FRepKey
        })
        this.fmodelDialog.listLoading = false
        this.fmodelDialog.formThead = res.Data
        // this.oriColumnData = res.Data
        this.fmodelDialog.formThead.map(item => {
          this.fmodelDialog.tableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        this.fmodelDialog.tableData = this.fmodelDialog.tableList.slice()
        // 获取显示表头键值对
        this.fmodelDialog.formThead.filter(item => {
          if (!item.frephide) {
            this.fmodelDialog.header.push(item.frepcap)
            this.fmodelDialog.headerKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        const listData = this.fmodelDialog.tableList.slice()
        // const listData = tableTemp.slice()
        listData.map((item, index) => {
          this.fmodelDialog.listData[index] = {}
          this.fmodelDialog.headerKeys.map(it => {
            this.fmodelDialog.listData[index][it] = item[it]
          })
        })
        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })
        this.fmodelDialog.dialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.fmodelDialog.listLoading = false
      }
    },
    async getFBumenMXHeaderAll () {
      try {
        this.fmodelDialog.listLoading = true
        this.fmodelDialog.header = []
        this.fmodelDialog.headerKeys = []
        this.fmodelDialog.listData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername,
          FRepKey
        })
        this.fmodelDialog.listLoading = false
        this.fmodelDialog.formThead = res.Data
        // this.oriColumnData = res.Data
        // this.tableList = []
        this.fmodelDialog.formThead.map(item => {
          this.fmodelDialog.tableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        // this.fmodelDialog.tableData = this.fmodelDialog.tableList.slice()
        // console.log(this.fmodelDialog.tableList, ' this.fmodelDialog.tableList')
        // console.log(this.fmodelDialog.tableData, ' this.fmodelDialog.tableData')
        let tableTemp
        if (this.fmodelDialog.selectedData.length) {
          tableTemp = this.fmodelDialog.selectedData
        } else {
          tableTemp = this.fmodelDialog.tableList.slice()
        }
        console.log(tableTemp, ' tableTemp')
        // 获取显示表头键值对
        this.fmodelDialog.formThead.filter(item => {
          if (!item.frephide) {
            this.fmodelDialog.header.push(item.frepcap)
            this.fmodelDialog.headerKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        // const listData = this.fmodelDialog.tableList.slice()
        const listData = tableTemp.slice()
        listData.map((item, index) => {
          this.fmodelDialog.listData[index] = {}
          this.fmodelDialog.headerKeys.map(it => {
            this.fmodelDialog.listData[index][it] = item[it]
          })
        })
        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })
        this.fmodelDialog.dialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.fmodelDialog.listLoading = false
      }
    },
    fmodelSelectionChange (val) {
      this.fmodelDialog.selectedData = val
    },
    async fmodelSizeChange (val) {
      this.fmodelDialog.currentPage = 1
      this.fmodelDialog.pagesize = val
      await this.getFBumenMX()
      await this.getFBumenMXHeader()
    },
    async fmodelCurrentChange (val) {
      this.fmodelDialog.currentPage = val
      await this.getFBumenMX()
      await this.getFBumenMXHeader()
    },
    // 导出数据
    async fmodelDownData () {
      await this.getFBumenMX()
      await this.getFBumenMXHeaderAll()
      this.header = this.fmodelDialog.header
      this.headerKeys = this.fmodelDialog.headerKeys
      this.listData = this.fmodelDialog.listData
      await this.exportDetailData('机型明细')
    },
    async cellDbclick ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
      console.log(row, ' row')
      console.log(this.fmodelDialog, ' this.fmodelDialog')
      if (column.field === 'fpowerkw') {
        this.fmodelDialog.fdetailModal = true
        this.fmodelDialog.fmodel = row.fpowerkw
        await this.getFBumenMX()
        await this.getFBumenMXHeader()
        }
      }
    },
    // 按钮点击
    async toolbarButtonClickEvent ({ code }) {
      const $grid = this.$refs.xGrid
      switch (code) {
        case 'myInsert':
          $grid.insert({

          })
          break
        // 保存
        case 'mySave':
          setTimeout(async () => {
            const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()

            if (insertRecords.length === 0 && updateRecords.length === 0 && removeRecords.length === 0) {
              VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'warning' })
              return
            }
            console.log(insertRecords, removeRecords, updateRecords, insertRecords.length > 0, updateRecords.length > 0, removeRecords.length > 0)
            try {
              const res = await vxetableGenAdd({ FRepKey, opername: this.opername, insertRecords, updateRecords, removeRecords })
              if (res.Error === 200) {
                this.getvxetableGenList()
                VXETable.modal.message({ content: `新增 ${insertRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
              } else {
                VXETable.modal.message({ content: res.Message, status: 'error' })
              }
            } catch (error) {
              console.log(error)
            }
          })
          break
        // 删除
        case 'myDelete':
          if ($grid.getCheckboxRecords().length === 0) {
            VXETable.modal.message({ content: `请选中一行`, status: 'warning' })
            return
          }
          setTimeout(async () => {
            const { removeRecords } = $grid.getRecordset()

            $grid.removeCheckboxRow()
            const res = await vxetableGenAdd({ FRepKey, opername: this.opername, removeRecords })
            if (res.Error === 0) {
              VXETable.modal.message({ content: ` 删除 ${removeRecords.length} 条`, status: 'success' })
              this.getvxetableGenList()
            }

            // $grid.clearSelected()
            // $grid.clearCheckboxRow()
          })
          break

        case 'myInsertTZ':

          break

        case 'myAA':
          VXETable.modal.message({ content: '新增', status: 'success' })
          break
      }
    },

    sumNum (list, field) { // DONE
      let count = 0
      list.forEach(item => {
        count += Number(item[field]) * 100
      })
      return (count / 100)
    },
    // 合计
    footerMethod ({ columns, data }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        this.aaValue = ''
        if (columnIndex === 0) {
          sums.push('合计')
        } else {
          this.oriColumnData.forEach((item, itemIndex) => {
            if (column.property === item.frepfld && item.frepsum === 1) {
              this.aaValue = item.frepfld
              return false
            }
          })
          if (column.property === this.aaValue) {
            sums.push(this.sumNum(data, column.property))
          } else {
            sums.push('')
          }
        }
      })
      // 返回一个二维数组的表尾合计
      return [sums]
    },

    formatAmount ({ cellValue }) {
      return cellValue ? `￥${XEUtils.commafy(XEUtils.toNumber(cellValue), { digits: 2 })}` : ''
    },
    formatDate ({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
    },
    checkColumnMethod ({ column }) {
      if (['nickname', 'role'].includes(column.property)) {
        return false
      }
      return true
    }

  }



</script>

